import time
import json
import uuid
import websocket
import threading
class limx_ws:

    def __init__(self, ACCID="WF_TRON1A_086", leg_ws_url = "ws://10.192.1.2:5000", open_notify=False):
        self.leg_ws_url = leg_ws_url
        self.ws_client = None
        self.open_notify = open_notify
        self.ACCID = ACCID

    def __on_open(self, ws):
        print("Connected legs!")

    def __on_close(self, ws, close_status_code, close_msg):
        """WebSocket 连接关闭回调"""
        print("Legs connected lost")

    def __on_message(self, ws, message):
        """WebSocket on_message callback"""
        try:
            msg_dict = json.loads(message)
            if msg_dict.get("title") == "notify_robot_info" and not self.open_notify:
                return
            print(f"Received message: {message}")
        except json.JSONDecodeError as e:
            print(f"Received message: {message}")
            print(f"Invalid JSON format: {e}")

    def __connect_tron1(self):
        """建立 WebSocket 连接"""
        self.ws_client = websocket.WebSocketApp(
            self.leg_ws_url,
            on_open=self.__on_open,
            on_message=self.__on_message,
            on_close=self.__on_close
        )
        self.ws_client.run_forever(ping_timeout=10)

    def __generate_guid(self):
        """生成唯一的 GUID"""
        return str(uuid.uuid4())

    def __create_message(self, ACCID, title, data=None):
        """创建一个 WebSocket 消息"""
        if data is None:
            data = {}  # 默认空字典
        return {
            "accid": ACCID,
            "title": title,
            "timestamp": int(time.time() * 1000),  # 当前时间戳（毫秒）
            "guid": self.__generate_guid(),
            "data": data
        }

    def __send_request(self, title, data=None):
        """发送 WebSocket 请求"""
        message = self.__create_message(self.ACCID, title, data)
        message_str = json.dumps(message)
        if self.ws_client:
            self.ws_client.send(message_str)

    def connect_legs(self):
        """启动 Tron1 WebSocket 连接的线程"""
        ws_thread = threading.Thread(target=self.__connect_tron1)
        ws_thread.daemon = False
        ws_thread.start()
        time.sleep(2)
    
    def stand(self):
        """请求站立模式"""
        self.__send_request("request_stand_mode")
        print("请求站立模式")

    def walk(self):
        """请求行走模式"""
        self.__send_request("request_walk_mode")
        print("请求行走模式")

    def twist(self, x:float, y:float, z:float):
        """请求移动指令"""
        self.__send_request("request_twist", {"x": x, "y": y, "z": z})
        print(f"请求移动指令  ，x: {x}, y: {y}, z: {z}")

    def sit(self):
        """请求坐下模式"""
        self.__send_request("request_sitdown")
        print("请求坐下模式")

    def stair(self):
        """楼梯模式请求"""
        self.__send_request("request_stair_mode", {"enable": True})
        print(f"请求启用楼梯模式: {True}")

    def stop(self):
        """紧急停止请求"""
        self.__send_request("request_emgy_stop")
        print("请求紧急停止")

    def imu(self):
        """IMU 开关请求"""
        self.__send_request("request_enable_imu", {"enable": True})
        print(f"请求启用 IMU: {True}")